package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Async
@Service
public class ApSearchServiceImpl implements ApSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public ResponseResult search(UserSearchDto dto) {

        SearchRequest request = new SearchRequest("app_info_article");
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        if (!StringUtils.isNotBlank(dto.getSearchWords())){
            query.must(QueryBuilders.matchAllQuery());
        }else {
            query.must(QueryBuilders.queryStringQuery(dto.getSearchWords())
                    .field("title")
                    .field("content")
                    .defaultOperator(Operator.OR));
        }


        query.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));

        request.source().query(query);

        request.source().from(0).size(dto.getPageSize());

        request.source().sort("publishTime", SortOrder.DESC);

        request.source().highlighter(new HighlightBuilder().field("title")
                                                            .preTags("<font style='color: red; font-size: inherit;'>")
                                                            .postTags("</font>"));
        SearchResponse searchResponse = null;
        try {
            searchResponse = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        SearchHit[] hits = searchResponse.getHits().getHits();

        ArrayList<Map> maps = new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            Map map = JSON.parseObject(sourceAsString, Map.class);

            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields != null && highlightFields.size() > 0){
                HighlightField title = highlightFields.get("title");
                Text[] texts = title.getFragments();
                String h_title = StringUtils.join(texts);
                map.put("h_title",h_title);
            }else {
                map.put("h_title",map.get("h_title"));
            }
            maps.add(map);
        }
        return ResponseResult.okResult(maps);
    }


    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult findUserSearch() {

        //获取用户
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //查询搜索记录
        List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(Criteria.where("userId").is(user.getId())).with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);

        return ResponseResult.okResult(apUserSearches);

    }
}
